import puppeteer, { Browser } from 'puppeteer';
import markdownService from './markdown';

class PageService {
    private browser: Browser | undefined;

    private async getPage({isMobile = true} = {}) {
        if (!this.browser) {
            this.browser = await puppeteer.launch();
        }
        const page = await this.browser.newPage();
        if (isMobile) {
            await page.setViewport({
                width: 375,
                height: 667,
                deviceScaleFactor: 2,
                isMobile: true
            })
            await page.setUserAgent(
                'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 '
                + '(KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1'
            );
        }
        return page;
    }

    async extractContents(url: string, {selector = '', simpleTag = true} = {} ) {
        const page = await this.getPage();
        await page.goto(url);

        const content = await page.evaluate(({selector}) => {
            return Array.from(document.body.querySelectorAll(selector))
                .map(dom => dom.innerHTML)
                .join('');
        }, {selector});

        // 剔除标签中的属性，保留纯粹的标签和文本
        let contentRet = simpleTag ? markdownService.simpleHtml(content) : content;

        await page.close();
        return contentRet;
    }
}

const pageService = new PageService();
export default pageService;